/********************************************************************************************************
 * @file	ota_server.c
 *
 * @brief	This is the source file for BLE SDK
 *
 * @author	BLE GROUP
 * @date	2020.06
 *
 * @par		Copyright (c) 2020, Telink Semiconductor (Shanghai) Co., Ltd.
 *			All rights reserved.
 *
 *			The information contained herein is confidential property of Telink
 *          Semiconductor (Shanghai) Co., Ltd. and is available under the terms
 *          of Commercial License Agreement between Telink Semiconductor (Shanghai)
 *          Co., Ltd. and the licensee or the terms described here-in. This heading
 *          MUST NOT be removed from this file.
 *
 *          Licensee shall not delete, modify or alter (or permit any third party to delete, modify, or
 *          alter) any information contained herein in whole or in part except as expressly authorized
 *          by Telink semiconductor (shanghai) Co., Ltd. Otherwise, licensee shall be solely responsible
 *          for any claim to the extent arising out of or relating to such deletion(s), modification(s)
 *      
 * 
 *          Licensees are granted free, non-transferable use of the information in this
 *          file under Mutual Non-Disclosure Agreement. NO WARRENTY of ANY KIND is provided.
 *
 *******************************************************************************************************/
#include "app_ota_server.h"
#include "app_keyboard_server.h"
#include "btl_poweron.h"
#include "app_parameter.h"


#define ONES_32				0xffffffff



uint8_t version_vel[8] = {'1','.','0','.','0','.','1','0'};
//const uint8_t version_vel[8] = {'1','.','0','.','0','.','1','4'};
uint8_t version_vel_size=sizeof(version_vel);
const uint8_t factory_version_vel[10] = {'1','.','0','.','0','.','1','7','_','1'};
//uint8_t honor[5] = {'h','o','n','o','r'};
const uint8_t otaPackageName[17] = {'Y','o','n','g','l','e','-','K','e','y','b','o','a','r','d','0','0'};
uint8_t device_version[4] = {'v','1','.','0'};
 
 
 
uint8_t sn_val[16]={'5','5','0','4','A','A','B','F','2','4','7','9','0','0','0','1'};

uint8_t ota_first_flag = 0;
uint8_t ota_state_flag = 0;

uint8_t server_data_first = 0;
uint8_t APP_OTA_Status = 0;
uint16_t len_buf=0;
uint8_t ota_sta_flag = 0;
uint8_t ota_slve_flag = 0;
uint16_t ota_data_vla = 0;
uint8_t ota_data_vla_yu = 0;


uint16_t ota_data_code = 0;

	uint32_t		ota_program_offset_a = WN8012_OTA_DATA_ADDRESS;

	ota_server_t_a 		blotaSvr_a_aaa;


	ota_server_honor 		blhonor_otaSvr_aaa;


uint8_t updata_buf[256]; /*升级用的临时数据备份区*/ 
uint8_t ota_code[215]; /*升级用的临时数据备份区*/ 

uint8_t temp_byte_offset = 0;

uint32_t ota_begin_tick;

uint32_t ota_led_tick=0;
uint8_t led_ota_caps = 0;
uint32_t ota_timeoout_tick;
uint8_t ota_timeout_test = 0;
uint32_t ota_reset_tick=0;
uint8_t ota_reset_flag=0;

UpgradeHead_Typedef upgrade_head_info;/*校验升级文件有关*/



void blt_ota_reset_aaa(void)
{
	blotaSvr_a_aaa.ota_step = OTA_STEP_IDLE;
	blotaSvr_a_aaa.ota_busy = 0;
	blotaSvr_a_aaa.pdu_len = 16;
	blotaSvr_a_aaa.version_accept = 0;
	blotaSvr_a_aaa.flow_mask = 0;
	//blotaSvr_a.resume_mode = 0;
	blotaSvr_a_aaa.data_pending_type = 0;
	blotaSvr_a_aaa.cur_adr_index = -1;
	blotaSvr_a_aaa.flash_addr_mark = -1;
	blotaSvr_a_aaa.fw_check_match = 0;
	blotaSvr_a_aaa.ota_start_tick = 0;
	blotaSvr_a_aaa.data_packet_tick = 0;
	blotaSvr_a_aaa.ota_connHandle = 0;
	blotaSvr_a_aaa.otaResult = OTA_SUCCESS;
	
	 ota_first_flag = 0;
	ota_state_flag = 0;

	 server_data_first = 0;
	 APP_OTA_Status = 0;
	 len_buf=0;
	 ota_sta_flag = 0;
	 ota_slve_flag = 0;
	 ota_data_vla = 0;
	 ota_data_vla_yu = 0;
}

void Delayed_Restart()
{

	if(ota_reset_flag&&ota_reset_tick>=500)
	{
		#if (APP_LOG_ALL_ENABLE == 1)
		printf("ota reset\n");
		#endif
		if(upgrade_head_info.rev_01 != 0)
		{
			uint8_t errCode = BTLTpPowerOnCheck();
			if(errCode==BTL_ERR_NEED_NOT_UPDATE||errCode==BTL_ERR_FW_UPDATED)
			{
				memset(&updata_buf[0],0xff,256);
				memcpy(&updata_buf[192],(uint8_t*)&upgrade_head_info,64);
				app_iwt_clr();
				app_spi_flash_page_program(ota_program_offset_a - WN8012_FLASH_PAGE_SIZE, updata_buf, 256);
			}
		}else{
			memset(&updata_buf[0],0xff,256);
			memcpy(&updata_buf[192],(uint8_t*)&upgrade_head_info,64);
			app_iwt_clr();
			app_spi_flash_page_program(ota_program_offset_a - WN8012_FLASH_PAGE_SIZE, updata_buf, 256);
		}

		app_iwt_clr();
		flash_log_flag=1;
		ota_first_flag = 0;
		task_log_notify_test();
		csi_system_reset();
	}
}


void blt_ota_procOtaFinish_aaa(void)
{
	//printf("blt_ota_procOtaFinish_aaa\n");


	if(blotaSvr_a_aaa.otaResult){  //OTA Fail
		/* need reboot for those SDK which can not process erasing Flash while BLE still works,
		 * For Eagle PUYA flash,  no need reboot, just tell peer device OTA fail and disconnect */
		if(blotaSvr_a_aaa.flash_addr_mark >= 0)
		{

			app_spi_flash_sector_or_block_erase(ota_program_offset_a-FLASH_SECTOR_SIZE,FLASH_SECTOR_SIZE);
		
			blt_ota_reset_aaa();  //must reset OTA flow status for next OTA
			csi_system_reset();
		}
	}
	else{ //OTA Success, must reboot
		/* attention: can not erase any data before new firmware start to work !!! */
//		 drv_flash_lock_config(AREA_00000_2FFFF);
//		 boot_flash_lock_flash(AREA_00000_2FFFF);

		rec_single_evt_test(MaintenanceServiceID,REMOTE_EVT_OTA_START,0x01,0x01,2);
//		csi_system_reset();
		ota_reset_flag=1;
		ota_reset_tick=0;
	}
}



int ota_save_data_aaa(uint32_t flash_addr, uint16_t len, uint8_t * data)
{
	if(flash_addr==0 && len>64)
	{
		memset(&updata_buf[0],0xff,256);
		memcpy(&updata_buf[192],data,64);
		app_iwt_clr();
		drv_flash_lock_config(UNLOCK);
		boot_flash_unlock_flash(UNLOCK);

		app_spi_flash_page_program(ota_program_offset_a - 2*WN8012_FLASH_PAGE_SIZE, updata_buf, 256);
//		memcpy((uint8_t*)&upgrade_head_info,data,64);
		temp_byte_offset=len-64;
		memset(&updata_buf[0],0xff,256);
		memcpy(&updata_buf[0],data+64,len-64);
		return OTA_SUCCESS;
	}
	//printf("temp_byte_offset %d len %d\n",temp_byte_offset,len);
	if(temp_byte_offset+len>=256)
	{
		memcpy(&updata_buf[temp_byte_offset],data,256-temp_byte_offset);
		//attention: Kite/Vulture now do not support across page write
		app_spi_flash_page_program(ota_program_offset_a + ((flash_addr-64)/256)*256,updata_buf, 256);
		//printf("write flash addr %2X\n",ota_program_offset_a + ((flash_addr-64)/256)*256);
		memset(updata_buf,0xff,256);
		memcpy(updata_buf,data+(256-temp_byte_offset),temp_byte_offset+len-256);
		temp_byte_offset = temp_byte_offset+len-256;
	}else{
		memcpy(&updata_buf[temp_byte_offset],data,len);
		temp_byte_offset+=len;
	}
	if(len == ota_data_vla_yu)
	{
		if(temp_byte_offset>0)
		{
			uint32_t write_flash_addr;
			if(temp_byte_offset>len)
			{
				write_flash_addr =  ota_program_offset_a + ((flash_addr-64)/256)*256;
			}else{
				write_flash_addr = ota_program_offset_a + (((flash_addr-64)/256)+1)*256;
			}

			app_spi_flash_page_program(write_flash_addr,updata_buf, 256);
		
			//printf("write flash addr %2X\n",write_flash_addr);
			//printf("temp_byte_offset %d\n",temp_byte_offset);

			temp_byte_offset=0;
		}

	}
	
	//printf("ota_program_offset_a+flash_addr==%2X\n",ota_program_offset_a + flash_addr-64);


	return OTA_SUCCESS;
}


uint32_t ValueInversion(uint32_t val)
{
	 uint8_t temp=0;
	 uint32_t dat=0;
	 temp = (val >> 24) & 0xff;
	 dat |= temp << 0;
	 temp = (val >> 16) & 0xff;
	 dat |= temp << 8;
	 temp = (val >> 8) & 0xff;
	 dat |= temp << 16;
	 temp = (val >> 0) & 0xff;
	 dat |= temp << 24;
	 return dat;
}

uint16_t ValueInversion_16(uint16_t val)
{
	 uint8_t temp=0;
	 uint16_t dat=0;
	 temp = (val >> 8) & 0xff;
	 dat |= temp << 0;
	 temp = (val) & 0xff;
	 dat |= temp << 8;

	 return dat;
}


/*
发送 09 05 消息给主机端
*/
bool ota_send_progress(void)
{
	uint8_t ucBuffer[14]={0};
	uint32_t curent_received_lenth =0;

	ucBuffer[0] = 0x09;
	ucBuffer[1] = 0x05;
	ucBuffer[2] = 0x01;
	ucBuffer[3] = 0x04;
	ucBuffer[4] = 0x00;
	ucBuffer[5] = 0x00;
	ucBuffer[6] = 0x00;
	ucBuffer[7] = 0x00;
	ucBuffer[8] = 0x02;
	ucBuffer[9] = 0x04;
	ucBuffer[10] = 0x00;
	ucBuffer[11] = 0x00;
	ucBuffer[12] = 0x00;
	ucBuffer[13] = 0x00;

	memcpy(&blhonor_otaSvr_aaa.package_valid_size,&blhonor_otaSvr_aaa.otabin_file_size,4);
	blhonor_otaSvr_aaa.package_valid_size=ValueInversion(blhonor_otaSvr_aaa.package_valid_size);
	
	memcpy(&ucBuffer[4],&blhonor_otaSvr_aaa.package_valid_size,4);
	//memcpy(&ptmp[10],&blhonor_otaSvr_aaa.received_file_size,4);
	
	curent_received_lenth = ota_data_code * 215 ;
	if (curent_received_lenth > blhonor_otaSvr_aaa.otabin_file_size)
	{
		curent_received_lenth = blhonor_otaSvr_aaa.otabin_file_size;
	}

	curent_received_lenth = ValueInversion(curent_received_lenth);
	memcpy(&ucBuffer[10],&curent_received_lenth,4);

	////printf("ptmp=%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\r\n", ptmp[0],ptmp[1],ptmp[2],ptmp[3],ptmp[4],ptmp[5], ptmp[6],ptmp[7],ptmp[8],ptmp[9],ptmp[10],ptmp[11],ptmp[12],ptmp[13]);
	bool status = one_wire_bus_app_custom_in_ack ( (uint8_t *)ucBuffer, 14);
	
	return status;
}
/*
发送 09 06 消息给主机端
*/
uint8_t ota_send_updateresult(uint8_t result)
{
	uint8_t ucBuffer[5]={0};
	ucBuffer[0] = 0x09;
	ucBuffer[1] = 0x06;
	ucBuffer[2] = 0x01;
	ucBuffer[3] = 0x01;
	ucBuffer[4] = result;
	/*ucBuffer[5] = 0x02;
	ucBuffer[6] = 0x02;
	ucBuffer[7] = 0x01;
	ucBuffer[8] = 0x01;*/

//	u_array_printf(ucBuffer,5);
	uint8_t status = one_wire_bus_app_custom_in_ack ( (uint8_t *)ucBuffer, 5);
	return status;
}



/**
 * @brief 计算一个数组的累加和
 * 
 * @param pdata    : 数据指针
 * @param n        : 数据长度
 * @return uint32_t : 结果
 */
uint32_t get_array_check_sum(uint8_t *pdata,uint32_t n)
{
	uint32_t temp_sum = 0;
	if(n){
		while(n--)
        {
			temp_sum += *pdata++;
		}
	}
	return temp_sum;
}

uint8_t updata_checksum(uint32_t fw_size)
{
	//printf("updata_checksum\n");
	uint8_t err_flag=0;
    uint32_t flash_addr, packet_sum = 0;
    uint8_t *pByteBuf;
	app_iwt_clr();
	
	memset(&upgrade_head_info, 0x00, sizeof(UpgradeHead_Typedef));
    app_spi_flash_page_read(ota_program_offset_a - WN8012_FLASH_PAGE_SIZE - WN8012_APP_HEAD_LENGTH,(uint8_t *)&upgrade_head_info,64);

	pByteBuf = (uint8_t *)&upgrade_head_info;
	if((upgrade_head_info.sync_one == APP_HEAD_SYSC_WORD_ONE) && (upgrade_head_info.sync_two == APP_HEAD_SYSC_WORD_TWO))
    {
        for(uint8_t n=0;n<63;n++)
        {
            packet_sum += pByteBuf[n];
        }
        if(upgrade_head_info.add != (packet_sum & 0xff))
        {
			//printf("check_sum %x packet_sum: %x\n",upgrade_head_info.add,packet_sum);
            err_flag |= 0x01; // 存储的帧头出错
        }else{
           
        }
    }else{
        err_flag |= 0x02; // 存储的帧头出错
    }
	if(upgrade_head_info.length > FLASH_APP_MAX_SIZE)
	{
		err_flag |= 0x04;  // APP长度超过Flash范围
		printf("upgrade_head_info.length %x fw_size: %x\n",upgrade_head_info.length,fw_size);
	}
	
	printf("upgrade_head_info.length %x fw_size: %x\n",upgrade_head_info.length,fw_size);
	if((err_flag == 0x00) && (upgrade_head_info.length > 0))
    {   
		
		uint32_t app_sum,app_rd_len;
        app_sum = 0x00;
        app_rd_len = 0x00;
        flash_addr = ota_program_offset_a;
        while(upgrade_head_info.length > app_rd_len)
        {
			app_iwt_clr();
            if((upgrade_head_info.length - app_rd_len) >= 256)
            {
//				memset(updata_buf,0,256);
                app_spi_flash_page_read(flash_addr + app_rd_len,updata_buf,256);                
                app_rd_len += 256;
                app_sum += get_array_check_sum(updata_buf,256);

            }else
            {
//				memset(updata_buf,0,256);
                uint32_t need_rd_len;
                need_rd_len = upgrade_head_info.length - app_rd_len ; 
                
                app_spi_flash_page_read(flash_addr + app_rd_len,updata_buf,need_rd_len);
				app_rd_len += need_rd_len;              

                app_sum += get_array_check_sum(updata_buf,need_rd_len);
            }
//			mdelay(5);
        }
		
			#if (APP_LOG_ALL_ENABLE == 1)
				printf("app_sum: %x upgrade_head_info.check_sum: %x\n",app_sum,upgrade_head_info.check_sum);
			#endif
        if(app_sum != upgrade_head_info.check_sum)
        {
            err_flag |= 0x08;  // APP校验和错误
        }   
		app_rd_len=0;
		app_sum=0;
		if(upgrade_head_info.rev_01 != 0)
		{
			for(uint32_t i=0; i < WN8012_TP_DATA_MAX_LENGTH/256; i++)
			{
				app_iwt_clr();
				app_spi_flash_page_read(WN8012_TP_OTA_DATA_ADDRESS + app_rd_len,updata_buf,256);   
				app_rd_len += 256;
				//256 byte OTA data32  half byteCRC
				app_sum += get_array_check_sum(updata_buf,256);
//				mdelay(5);
			}
			#if (APP_LOG_ALL_ENABLE == 1)
				printf("tp_sum: %x upgrade_head_info.tp_sum: %x\n",app_sum,upgrade_head_info.rev_01);
			#endif
				if(app_sum != upgrade_head_info.rev_01)
				{
					err_flag |= 0x10;  // APP校验和错误
				}
		}
	}
	rec_single_evt_test(MaintenanceServiceID,REMOTE_EVT_CHARGE_STA,0x01,0x01,err_flag);
	printf("err_flag %x\n",err_flag);
	return err_flag;
}

/**
 * @brief 单总线计时时基
 * 
 */
void app_ota_timer_tick_0_1ms_handler(void)
{
	ota_begin_tick++;
	ota_led_tick++;
	ota_timeoout_tick++;
	ota_reset_tick++;
}

void ota_data_init(void)
{
	uint8_t ptmp[60]={0};
	uint8_t write_buf[20]={0};

	if(ota_first_flag){
		if(ota_led_tick> 2000){
			ota_led_tick = 0;
//			led_ota_caps = ~led_ota_caps;
			app_key_led_set_mode(LED_CAPS, led_ota_caps);
			if(led_ota_caps)
			{
				led_ota_caps=0;
			}else{
				led_ota_caps=1;
			}
		}
//		reset_idle_status();
	}
	
	if(ota_state_flag){
		
		ptmp[0] = 0x01;
		ptmp[1] = 0x07;
		ptmp[2] = 0x03;
		ptmp[3] = 0x04;
		memcpy(&ptmp[4],device_version,4);
		ptmp[8] = 0x07;

//		ptmp[7] = 0x07;
//		memcpy(&ptmp[8],version_vel,7);
//		ptmp[15] = 0x09;
//		ptmp[16] = 0x10;
//		memcpy(&ptmp[17],sn_val,16);
//		ptmp[33] = 0x0f;
//		ptmp[34] = 0x10;
//		memcpy(&ptmp[35],otaPackageName,16);
		ptmp[9] = 0x08;
		memcpy(&ptmp[10],version_vel,8);
		ptmp[18] = 0x09;
		ptmp[19] = 0x10;
		memcpy(&ptmp[20],sn_val,16);
		ptmp[36] = 0x0f;
		ptmp[37] = 0x10;
		memcpy(&ptmp[38],otaPackageName,17);

//		u_array_printf(ptmp,50);
		bool status = one_wire_bus_app_custom_in_ack (ptmp, 55);//49
		if(status == true){
//			u_array_printf(ptmp,50);
			ota_state_flag = 0;
		}else{
			//printf("status = %2x\n",status);
		}
	}


	if(server_data_first &&	ota_begin_tick>100 )
	{
		uint32_t temp=0;
		app_spi_flash_page_read(FLASH_OTA_BASE_ADDR, (uint8_t*)&temp, 4);

	
		if(temp!=0xffffffff)
		{
			app_iwt_clr();
			drv_flash_lock_config(UNLOCK);
			boot_flash_unlock_flash(UNLOCK);
			app_spi_flash_sector_or_block_erase(FLASH_OTA_BASE_ADDR - FLASH_SECTOR_SIZE,FLASH_BLOCK64_SIZE);
			app_iwt_clr();
			drv_flash_lock_config(AREA_00000_2FFFF);
			boot_flash_lock_flash(AREA_00000_2FFFF);
			app_iwt_clr();
		}

		ptmp[0] = 0x09;
		ptmp[1] = 0x05;
		ptmp[2] = 0x01;
		ptmp[3] = 0x04;
		ptmp[4] = 0x00;
		ptmp[5] = 0x00;
		ptmp[6] = 0x00;
		ptmp[7] = 0x00;
		ptmp[8] = 0x02;
		ptmp[9] = 0x04;
		ptmp[10] = 0x00;
		ptmp[11] = 0x00;
		ptmp[12] = 0x00;
		ptmp[13] = 0x00;
		//blhonor_otaSvr_aaa.package_valid_size=ValueInversion(blhonor_otaSvr_aaa.package_valid_size);
		memcpy(&blhonor_otaSvr_aaa.package_valid_size,&blhonor_otaSvr_aaa.otabin_file_size,4);
		blhonor_otaSvr_aaa.package_valid_size=ValueInversion(blhonor_otaSvr_aaa.package_valid_size);
		//blhonor_otaSvr_aaa.received_file_size=ValueInversion(blhonor_otaSvr_aaa.received_file_size);
		
		memcpy(&ptmp[4],&blhonor_otaSvr_aaa.package_valid_size,4);
		//memcpy(&ptmp[10],&blhonor_otaSvr_aaa.received_file_size,4);
		
		////printf("ptmp=%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\r\n", ptmp[0],ptmp[1],ptmp[2],ptmp[3],ptmp[4],ptmp[5], ptmp[6],ptmp[7],ptmp[8],ptmp[9],ptmp[10],ptmp[11],ptmp[12],ptmp[13]);
		bool status = one_wire_bus_app_custom_in_ack ( (uint8_t *)ptmp, 14);
		if(status == true){
			//APP_OTA_Status = 0;
		}

		write_buf[0] = 0x09;
		write_buf[1] = 0x03;
		write_buf[2] = 0x01;
		write_buf[3] = 0x04;
		write_buf[4] = 0x00;
		write_buf[5] = 0x00;
		write_buf[6] = 0x00;
		write_buf[7] = 0x00;
		write_buf[8] = 0x02;
		write_buf[9] = 0x04;
		write_buf[10] = 0x00;
		write_buf[11] = 0x00;
		write_buf[12] = 0x00;
		write_buf[13] = 0x00;
		blhonor_otaSvr_aaa.ota_length_a = 0x000000d7;
		blhonor_otaSvr_aaa.ota_offset_a = 0x000001e6;
		//blhonor_otaSvr_aaa.ota_offset_a=ValueInversion(blhonor_otaSvr_aaa.ota_offset_a);

		//memcpy(&write_buf[4],&blhonor_otaSvr_aaa.ota_offset_a,4);
		write_buf[4] = blhonor_otaSvr_aaa.ota_offset_a>>24;
		write_buf[5] = blhonor_otaSvr_aaa.ota_offset_a>>16;
		write_buf[6] = blhonor_otaSvr_aaa.ota_offset_a>>8;
		write_buf[7] = blhonor_otaSvr_aaa.ota_offset_a;
//		blhonor_otaSvr_aaa.ota_length_a=ValueInversion(blhonor_otaSvr_aaa.ota_length_a);
		write_buf[10] = blhonor_otaSvr_aaa.ota_length_a>>24;
		write_buf[11] = blhonor_otaSvr_aaa.ota_length_a>>16;
		write_buf[12] = blhonor_otaSvr_aaa.ota_length_a>>8;
		write_buf[13] = blhonor_otaSvr_aaa.ota_length_a;
		
//		memcpy(&write_buf[10],&blhonor_otaSvr_aaa.ota_length_a,4);
		
		////printf("write_buf=%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\r\n", write_buf[0],write_buf[1],write_buf[2],write_buf[3],write_buf[4],write_buf[5], write_buf[6],write_buf[7],write_buf[8],write_buf[9],write_buf[10],write_buf[11],write_buf[12],write_buf[13]);
		bool status1 = one_wire_bus_app_custom_in_ack ( (uint8_t *)write_buf, 14);
		if(status1 == true){
			ota_data_code = 1;
			server_data_first = 0;
			APP_OTA_Status = 0;
//			blhonor_otaSvr_aaa.ota_length_tset = 0;
		}
	}


	if(ota_slve_flag && ota_begin_tick>=600 )
	{
		if(ota_sta_flag)
		{
			blhonor_otaSvr_aaa.ota_offset_slaver = blhonor_otaSvr_aaa.ota_offset_a - 0x1e6;
			if(blhonor_otaSvr_aaa.ota_offset_slaver<blhonor_otaSvr_aaa.otabin_file_size){
				blotaSvr_a_aaa.flash_addr_mark = blhonor_otaSvr_aaa.ota_offset_slaver;
				ota_save_data_aaa (blhonor_otaSvr_aaa.ota_offset_slaver, blhonor_otaSvr_aaa.ota_length_tset, ota_code);
			}
			ota_sta_flag=0;
		}

		//if(ota_begin_tick>=500)
		{
			ota_begin_tick = 0;

			write_buf[0] = 0x09;
			write_buf[1] = 0x03;
			write_buf[2] = 0x01;
			write_buf[3] = 0x04;
			write_buf[4] = 0x00;
			write_buf[5] = 0x00;
			write_buf[6] = 0x00;
			write_buf[7] = 0x00;
			write_buf[8] = 0x02;
			write_buf[9] = 0x04;
			write_buf[10] = 0x00;
			write_buf[11] = 0x00;
			write_buf[12] = 0x00;
			write_buf[13] = 0x00;

			blhonor_otaSvr_aaa.ota_length_a = 0x000000d7;
	//		//printf("ota_data_code = %d\n",ota_data_code);
	//			if(ota_data_code == (ota_data_vla+1))
			if(ota_data_code == (ota_data_vla))
			{
				blhonor_otaSvr_aaa.ota_length_a = ota_data_vla_yu;
			}
	//		if(ota_data_code>(ota_data_vla+1))
			if(ota_data_code>(ota_data_vla))
			{
	//				ota_first_flag = 0;
				ota_slve_flag = 0;
				if(updata_checksum(blhonor_otaSvr_aaa.otabin_file_size))
				{
					memset(&upgrade_head_info, 0x00, sizeof(UpgradeHead_Typedef));
					blotaSvr_a_aaa.otaResult = 1;
					ota_send_updateresult(0x00);
	//					app_spi_flash_sector_or_block_erase(ota_program_offset_a-FLASH_SECTOR_SIZE,FLASH_SECTOR_SIZE);
					ota_reset_flag=1;
					ota_reset_tick=0;
					rec_single_evt_test(MaintenanceServiceID,REMOTE_EVT_OTA_START,0x01,0x01,3);
				}else{
					blotaSvr_a_aaa.otaResult = 0;
					ota_send_updateresult(0x01);
					rec_single_evt_test(MaintenanceServiceID,REMOTE_EVT_OTA_START,0x01,0x01,2);
				}

				//printf("blotaSvr_a_aaa.otaResult=====%2x\n",blotaSvr_a_aaa.otaResult);

	//			blt_ota_procOtaFinish_aaa();
				return;
			}

			
			blhonor_otaSvr_aaa.ota_offset_a = blhonor_otaSvr_aaa.ota_offset_a + blhonor_otaSvr_aaa.ota_length_tset;
	
			write_buf[4] = blhonor_otaSvr_aaa.ota_offset_a>>24;
			write_buf[5] = blhonor_otaSvr_aaa.ota_offset_a>>16;
			write_buf[6] = blhonor_otaSvr_aaa.ota_offset_a>>8;
			write_buf[7] = blhonor_otaSvr_aaa.ota_offset_a;
			//blhonor_otaSvr_aaa.ota_length_a=ValueInversion(blhonor_otaSvr_aaa.ota_length_a);
			write_buf[10] = blhonor_otaSvr_aaa.ota_length_a>>24;
			write_buf[11] = blhonor_otaSvr_aaa.ota_length_a>>16;
			write_buf[12] = blhonor_otaSvr_aaa.ota_length_a>>8;
			write_buf[13] = blhonor_otaSvr_aaa.ota_length_a;

			blhonor_otaSvr_aaa.ota_length_tset = blhonor_otaSvr_aaa.ota_length_a;
			bool status = one_wire_bus_app_custom_in_ack ( (uint8_t *)write_buf, 14);
			if(status == true){
				ota_slve_flag = 0;
				ota_sta_flag = 0;
				ota_data_code++;
			}
	//		//printf("ota_data_code=====%d\n",ota_data_code);

		}
	}
	
	Delayed_Restart();


//	if((ota_timeoout_tick>=10000) && (ota_first_flag))
//		{
//		ota_timeoout_tick = 0;
//		ota_timeout_test++;
//
//		if(ota_timeout_test>=240){
//			ota_first_flag = 0;
//			ota_timeout_test = 0;
//			server_data_first = 0;
//			APP_OTA_Status = 0;
//			len_buf = 0;
//			ota_slve_flag = 0;
//			ota_data_vla = 0;
//			ota_data_vla_yu = 0;
//			memset(&blhonor_otaSvr_aaa, 0, sizeof(blhonor_otaSvr_aaa));
//			blt_ota_reset_aaa();
//			//printf("ota_timeout\n");
//		}
//	}
}

void otaWrite_honor( void * p, uint16_t len)
{
	
	SourcePacketStr *pAttDat = (SourcePacketStr*)p;
	
	uint16_t ota_cmd_adr =  pAttDat->cid | (pAttDat->sid<<8);
	int err_flag = OTA_SUCCESS;
	uint8_t ptmp[32]={0};

	blhonor_otaSvr_aaa.error_code = 100000;
	blhonor_otaSvr_aaa.battery_threshold = 30;
	blhonor_otaSvr_aaa.app_wait_Timeout_s_a = 30;
	blhonor_otaSvr_aaa.device_restart_Timeout_s_a = 50;
	blhonor_otaSvr_aaa.ota_unit_size_a = 224;
	blhonor_otaSvr_aaa.interval = 20;
	blhonor_otaSvr_aaa.ack_enable = 1;
	blhonor_otaSvr_aaa.received_file_size = 0;
	//printf("ota_cmd_adr=%02X\r\n", ota_cmd_adr);
	if(ota_cmd_adr == HN_CMD_OTA_START)	//0901
	{
		ota_first_flag = 1;	
		ptmp[0] = 0x09;
		ptmp[1] = 0x01;
		ptmp[2] = 0x7F;
		ptmp[3] = 0x04;
		blhonor_otaSvr_aaa.error_code=ValueInversion(blhonor_otaSvr_aaa.error_code);
		memcpy(&ptmp[4],&blhonor_otaSvr_aaa.error_code,4);
		

		ptmp[8] = 0x04;
		ptmp[9] = 0x01;
		ptmp[10] = blhonor_otaSvr_aaa.battery_threshold;
		bool status = one_wire_bus_app_custom_in_ack( (uint8_t *)ptmp, 11);
		if(status == true){
			
		}
	}
	else if(ota_cmd_adr == HN_CMD_OTA_PARAM)//0902
	{
		////printf("ota_cmd_adr=%02X\r\n", ota_cmd_adr);
		ptmp[0] = 0x09;
		ptmp[1] = 0x02;
		ptmp[2] = 0x01;
		ptmp[3] = 0x02;
		blhonor_otaSvr_aaa.app_wait_Timeout_s_a=ValueInversion_16(blhonor_otaSvr_aaa.app_wait_Timeout_s_a);
		memcpy(&ptmp[4],&blhonor_otaSvr_aaa.app_wait_Timeout_s_a,2);

		ptmp[6] = 0x02;
		ptmp[7] = 0x02;
		blhonor_otaSvr_aaa.device_restart_Timeout_s_a=ValueInversion_16(blhonor_otaSvr_aaa.device_restart_Timeout_s_a);
		memcpy(&ptmp[8],&blhonor_otaSvr_aaa.device_restart_Timeout_s_a,2);

		ptmp[10] = 0x03;
		ptmp[11] = 0x02;
		blhonor_otaSvr_aaa.ota_unit_size_a=ValueInversion_16(blhonor_otaSvr_aaa.ota_unit_size_a);
		memcpy(&ptmp[12],&blhonor_otaSvr_aaa.ota_unit_size_a,2);

		ptmp[14] = 0x04;
		ptmp[15] = 0x02;
		blhonor_otaSvr_aaa.interval=ValueInversion_16(blhonor_otaSvr_aaa.interval);
		memcpy(&ptmp[16],&blhonor_otaSvr_aaa.interval,2);

		ptmp[18] = 0x05;
		ptmp[19] = 0x01;
		
		memcpy(&ptmp[20],&blhonor_otaSvr_aaa.ack_enable,1);

		
		////printf("ptmp=%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\r\n", ptmp[0],ptmp[1],ptmp[2],ptmp[3],ptmp[4],ptmp[5], ptmp[6],ptmp[7],ptmp[8],ptmp[9],ptmp[10],ptmp[11],ptmp[12], ptmp[13],ptmp[14],ptmp[15],ptmp[16],ptmp[17],ptmp[18],ptmp[19],ptmp[20],ptmp[21]);
		bool status = one_wire_bus_app_custom_in_ack ( (uint8_t *)ptmp, 21);
		if(status == true){
			blhonor_otaSvr_aaa.APP_OTA_Status = 1;
			rec_single_evt_test(MaintenanceServiceID,REMOTE_EVT_OTA_START,0x01,0x01,1);
		}

	}
	else if(ota_cmd_adr == HN_CMD_OTA_DATA)//0903
	{
		uint32_t ota_offset;
		uint32_t ota_length;
		uint8_t datalen=0;
		for(uint8_t i=0;i<len-2;)
		{
			 switch(pAttDat->data[i])
			{
				case 0x01:      //设备侧申请数据起始地址  
						datalen=pAttDat->data[i+1];
						memcpy(&ota_offset,&(pAttDat->data[i+2]),datalen);
						ota_offset = ValueInversion(ota_offset);
						i+=(datalen+2);
				break;
				case 0x02: 			//设备侧申请数据长度
					datalen=pAttDat->data[i+1];
						memcpy(&ota_length,&(pAttDat->data[i+2]),datalen);
						ota_length = ValueInversion(ota_length);
						i+=(datalen+2);
				break;        
				case 0x03:       			// 申请文件bitmap
						datalen=pAttDat->data[i+1];
						
						i+=(datalen+2);
				break;
				
				default:
					break;
			}
		}
		#if APP_OTA_UPDATA_LOG
			printf("ota_offset = %4x\n",ota_offset);
			printf("ota_length = %4x\n",ota_length);
			printf("ota_offset_a = %4x\n",blhonor_otaSvr_aaa.ota_offset_a);
			printf("ota_length_a = %4x\n",blhonor_otaSvr_aaa.ota_length_a);
			
		#endif
		if((blhonor_otaSvr_aaa.ota_offset_a==ota_offset)&&(blhonor_otaSvr_aaa.ota_length_a==ota_length))
		{
			#if APP_OTA_UPDATA_LOG
				printf("ota_length_tset = %4x\n",blhonor_otaSvr_aaa.ota_length_tset);
			#endif
			ota_sta_flag=1;
			if(kb_ack_flag)
			{
				kb_ack_flag=0;
			}
		}
		
		
		
	} 
	else if(ota_cmd_adr == HN_CMD_OTA_CANCEL)  //0908
	{
		ota_first_flag = 0;
		ota_timeout_test = 0;
		server_data_first = 0;
		APP_OTA_Status = 0;
		len_buf = 0;
		ota_slve_flag = 0;
		ota_data_vla = 0;
		ota_data_vla_yu = 0;
		memset(&blhonor_otaSvr_aaa, 0, sizeof(blhonor_otaSvr_aaa));
		blt_ota_reset_aaa();
		pad_cover_state = 0;
		pad_lcd_state = 1;
		app_led_ctrl(keyboard_led_status);
	}
	else if(ota_cmd_adr == HN_CMD_OTA_STATUS)//0909
	{
		uint8_t write_buf[2]={0};
		write_buf[0] = 0x09;
		write_buf[1] = 0x00;
		memcpy(&write_buf[1],&blhonor_otaSvr_aaa.APP_OTA_Status,1);
		one_wire_bus_app_custom_in_ack( (uint8_t *)write_buf, 2);
		blhonor_otaSvr_aaa.ota_length_a = 0x01e6;

//		//printf("blhonor_otaSvr_aaa.ota_length_a == %d\n",blhonor_otaSvr_aaa.ota_length_a);
		if(blhonor_otaSvr_aaa.ota_length_a == 486)
		{
			ptmp[0] = 0x09;
			ptmp[1] = 0x03;
			ptmp[2] = 0x01;
			ptmp[3] = 0x04;
			ptmp[4] = 0x00;
			ptmp[5] = 0x00;
			ptmp[6] = 0x00;
			ptmp[7] = 0x00;
			ptmp[8] = 0x02;
			ptmp[9] = 0x04;
			ptmp[10] = 0x00;
			ptmp[11] = 0x00;
			ptmp[12] = 0x00;
			ptmp[13] = 0x00;
			
			blhonor_otaSvr_aaa.ota_length_a=ValueInversion(blhonor_otaSvr_aaa.ota_length_a);
			memcpy(&ptmp[10],&blhonor_otaSvr_aaa.ota_length_a,4);

			bool status = one_wire_bus_app_custom_in_ack ( (uint8_t *)ptmp, 14);
			if(status == true){
				APP_OTA_Status = 1;
				len_buf = 0;
				ota_timeout_test = 0;
			}

		}
		else
		{

		}


		
	}
	else if(ota_cmd_adr == HN_CMD_OTA_FILE_CONTENT)//0904
	{

		ota_first_flag = 1;	
		//printf("len=%d\r\n", len);
//		//printf("APP_OTA_Status %d\r\n", APP_OTA_Status);
		if(APP_OTA_Status){
			len_buf = len_buf+len;

//			if(len_buf == 0xec)
			if(pAttDat->data[0]==0)
			{
				memcpy(&blhonor_otaSvr_aaa.otabin_file_size,&pAttDat->data[193],4);
				//blhonor_otaSvr_aaa.otabin_file_size=ValueInversion(blhonor_otaSvr_aaa.otabin_file_size);

				//printf("blhonor_otaSvr_aaa.otabin_file_size=%02X\r\n", pAttDat->data[193]);
				//printf("blhonor_otaSvr_aaa.otabin_file_size1=%02X\r\n", pAttDat->data[194]);
				//printf("blhonor_otaSvr_aaa.otabin_file_size2=%02X\r\n", pAttDat->data[195]);
				//printf("blhonor_otaSvr_aaa.otabin_file_size3=%02X\r\n", pAttDat->data[196]);
				//printf("blhonor_otaSvr_aaa.otabin_file_size=%02X\r\n", blhonor_otaSvr_aaa.otabin_file_size);

				if(blhonor_otaSvr_aaa.otabin_file_size>64*1024)
				{
					blhonor_otaSvr_aaa.otabin_file_size = 52*1024;
				}
				

				ota_data_vla = blhonor_otaSvr_aaa.otabin_file_size/215;
				ota_data_vla_yu = blhonor_otaSvr_aaa.otabin_file_size%215;
				//printf("ota_data_vla=%d\r\n", ota_data_vla);
				//printf("ota_data_vla_yu=%d\r\n", ota_data_vla_yu);
				
//				memcpy(hash2,&pAttDat->dat[199],20);
			}else
//			if(len_buf == 0x1d8)
			if(pAttDat->data[0]==1)
			{
//				memcpy(&hash2[19],&pAttDat->dat[3],12);
				
			//	//printf("hash222222222222222222222222=%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%\r\n", hash2[0],hash2[1],hash2[2],hash2[3],hash2[4],hash2[5], hash2[6],hash2[7],hash2[8],hash2[9],hash2[10],hash2[11]);
			}
			
			//printf("len_buf=%d\r\n", len_buf);
			if(len_buf == 495){
				server_data_first = 1;
				ota_begin_tick=0;
				//ota_first_flag = 1;
			}
			
		}
		else //if(len == 218)
		{
			if((len) == 218){
				blhonor_otaSvr_aaa.ota_length_tset = 215;
			}
			
			if(err_flag == OTA_SUCCESS){
				
				if(ota_sta_flag &&!ota_slve_flag)
				{
					memcpy(ota_code,&pAttDat->data[1],blhonor_otaSvr_aaa.ota_length_tset);
					ota_slve_flag = 1;
					
				}

			}
			//ota_send_progress();
		}


		

	}
	else if(ota_cmd_adr == HN_CMD_OTA_SIZE)//0905
	{
	
	}else if(ota_cmd_adr==0x0906){

			blt_ota_procOtaFinish_aaa();

	}
	
}





















